import {Work} from '../../../db/models/work'
import {sendError, sendSuccess} from "../../utils/responseHandler";

export default async function handler(req, res) {
    const {id} = req.query;

    if (req.method === 'DELETE') {
        try {
            const work = await Work.findByPk(id);
            if (work) {
                await work.destroy();
                sendSuccess(res, '1');
            } else {
                sendError(res, '岗位不存在', 404);
            }
        } catch (error) {
            sendError(res, '删除失败', 500);
        }
    } else if (req.method === 'PUT') {
        try {
            const work = await Work.findByPk(id);
            if (work.work_status === 0) {
                sendError(res, '该岗位还未进行审核,请耐心等待！', 401);
            } else if (work.work_status === 2) {
                sendError(res, '该岗位审核未通过,并不能手动下架', 401);
            } else if (work.work_status === 3) {
                sendError(res, '该岗位已下架,无需再次点击', 401);
            } else if (work && work.work_status === 1) {
                await work.update({work_status: 3}, {where: {id}});
                sendSuccess(res, '1');
            } else {
                sendError(res, '岗位不存在', 401);
            }
        } catch (error) {
            sendError(res, '删除失败', 500);
        }
    } else {
        // 不支持其他方法
        res.setHeader('Allow', ['PUT', 'DELETE']);
        res.status(405).end(`Method ${req.method} Not Allowed`);
    }
}
